﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Bzzb.Model;
using FreeSql.Internal.Model;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Core.Extension;
using Magicodes.ExporterAndImporter.Excel;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OfficeOpenXml;

namespace Bzzb.Controllers
{
    public class CheLiangGuZhangController : BaseController
    {
        private readonly IWebHostEnvironment _env;
        private readonly IConfiguration _configuration;
        private readonly ILogger<CheLiangGuZhangController> _logger;
        public CheLiangGuZhangController(ILogger<CheLiangGuZhangController> logger, IFreeSql fsql, IConfiguration configuration, IWebHostEnvironment env) : base(fsql)
        {
            this._env = env;
            this._logger = logger;
            this._configuration = configuration;
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Index([FromForm] long bzcltid, [FromForm] long bzclid, [FromForm] string content, [FromForm] int pageNumber = 1, [FromForm] int pageSize = 10)
        {
            DynamicFilterInfo dyfilter = JsonConvert.DeserializeObject<DynamicFilterInfo>(@"
{
  'Logic' : 'Or',
  'Filters' :
  [
    {
      'Field' : 'zbwybm',
      'Operator' : 'Contains',
      'Value' : '" + content + @"',
    },
    {
      'Field' : 'mc',
      'Operator' : 'Contains',
      'Value' : '" + content + @"',
    },
    {
      'Field' : 'gzxx',
      'Operator' : 'Contains',
      'Value' : '" + content + @"',
    },
    {
      'Field' : 'gzyy',
      'Operator' : 'Contains',
      'Value' : '" + content + @"',
    },
    {
      'Field' : 'gzjmc',
      'Operator' : 'Contains',
      'Value' : '" + content + @"',
    }
  ]
}
");
            List<CheLiangGuZhang> cheliangguzhangs = await _fsql.Select<CheLiangGuZhang>().Where(clgz => clgz.Bzclid == bzclid && clgz.Bzcltid == bzcltid).WhereDynamicFilter(dyfilter).Count(out var total).Page(pageNumber, pageSize).ToListAsync();
            _logger.LogInformation(_fsql.Select<CheLiangGuZhang>().ToSql());
            JObject data = new();
            data.Add("total", total);
            data.Add("list", JArray.FromObject(cheliangguzhangs));
            return RenderJson(data: data);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Save([FromForm] CheLiangGuZhang cheliangguzhang)
        {
            long id = await _fsql.Insert(cheliangguzhang).ExecuteIdentityAsync();
            cheliangguzhang.Id = id;

            return RenderJson(data: cheliangguzhang);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Delete([FromForm] long id) {
            int affrows = await _fsql.Delete<CheLiangGuZhang>().Where(clgz => clgz.Id == id).ExecuteAffrowsAsync();
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Update([FromForm] CheLiangGuZhang cheliangguzhang) {
            int affrows = await _fsql.Update<CheLiangGuZhang>().SetSourceIgnore(cheliangguzhang, colval => colval == null).ExecuteAffrowsAsync();
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Show([FromForm] long id) {
            CheLiangGuZhang cheliangguzhang = await _fsql.Select<CheLiangGuZhang>().Where(clgz => clgz.Id == id).ToOneAsync();
            return RenderJson(data: cheliangguzhang);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> DownloadExcelTemplate()
        {
            BaoZhangZhuangBeiType baozhangzhuangbeitype = await _fsql.Select<BaoZhangZhuangBeiType>().Where(bzzbt => bzzbt.Id == 1).ToOneAsync();
            JObject jo_fieldinfo = JObject.Parse(baozhangzhuangbeitype.Gzfieldinfo);
            IExcelExporter exporter = new ExcelExporter();
            var filePath = @"wwwroot/download/guzhang/车辆故障模板.xlsx";
            var arr = new[] { /*jo_fieldinfo.GetValue("zbwybm").ToString(), jo_fieldinfo.GetValue("mc").ToString(), jo_fieldinfo.GetValue("xh").ToString(), jo_fieldinfo.GetValue("bh").ToString(),*/ jo_fieldinfo.GetValue("fxrq").ToString(), jo_fieldinfo.GetValue("pcrq").ToString(), jo_fieldinfo.GetValue("gzxx").ToString(), jo_fieldinfo.GetValue("gzyy").ToString(), jo_fieldinfo.GetValue("gzfswz").ToString(), jo_fieldinfo.GetValue("gzjmc").ToString(), jo_fieldinfo.GetValue("gzjxh").ToString(), jo_fieldinfo.GetValue("gzjhm").ToString(), jo_fieldinfo.GetValue("gzjzjrq").ToString(), jo_fieldinfo.GetValue("gzjgzsj").ToString(), jo_fieldinfo.GetValue("pcff").ToString(), jo_fieldinfo.GetValue("pgr").ToString(), jo_fieldinfo.GetValue("pggs").ToString(), jo_fieldinfo.GetValue("ghjmc").ToString(), jo_fieldinfo.GetValue("ghjxh").ToString(), jo_fieldinfo.GetValue("ghjhm").ToString(), jo_fieldinfo.GetValue("ghjsysj").ToString() };
            var sheetName = "车辆故障";
            var result = await exporter.ExportHeaderAsByteArray(arr, sheetName);
            result.ToExcelExportFileInfo(filePath);
            JObject data = new();
            data.Add("url", _configuration.GetValue<string>("UploadUrl") + $"/download/guzhang/车辆故障模板.xlsx");
            return RenderJson(data: data);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> ExportExcel([FromForm] long bzcltid, [FromForm] long bzclid)
        {
            IExporter exporter = new ExcelExporter();
            var result = await exporter.Export(@"wwwroot/download/guzhang/车辆故障.xlsx", await _fsql.Select<CheLiangGuZhang>().Where(clgz => clgz.Bzcltid == bzcltid && clgz.Bzclid == bzclid).ToListAsync());

            JObject data = new();
            data.Add("url", _configuration.GetValue<string>("UploadUrl") + $"/download/guzhang/车辆故障.xlsx");
            return RenderJson(data: data);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> ImportExcel([FromForm] long bzcltid, [FromForm] long bzclid, [FromForm] string filePath)
        {
            //filePath = @"upload/excel/车辆故障模板.xlsx";
            string webrootpath = _env.WebRootPath;
            FileInfo file = new FileInfo(Path.Combine(webrootpath, filePath));

            long affrows = 0;
            _fsql.Transaction(() => {
                try
                {
                    using (ExcelPackage package = new ExcelPackage(file))
                    {
                        ExcelWorksheet worksheet = package.Workbook.Worksheets.First();
                        int rowCount = worksheet.Dimension.Rows;
                        var items = new List<CheLiangGuZhang>();
                        for (int row = 2; row <= rowCount; row++)
                        {
                            string xh = "";
                            string ssbm = "";
                            string cph = "";
                            string mc = "";
                            // 1.保障车辆(1-电源车 2-加油车) 2.保障设备 3.保障构件车辆 4.保障构件设备
                            if (bzcltid == 1)
                            {
                                DianYuanChe dianyuanche = _fsql.Select<DianYuanChe>().Where(dyc => dyc.Id == bzclid).ToOne();
                                xh = dianyuanche.Xh;
                                ssbm = dianyuanche.Bzclwybm;
                                cph = dianyuanche.Cph;
                                mc = dianyuanche.Clmc;
                            }
                            if (bzcltid == 2)
                            {
                                JiaYouChe jiayouche = _fsql.Select<JiaYouChe>().Where(jyc => jyc.Id == bzclid).ToOne();
                                xh = jiayouche.Xh;
                                ssbm = jiayouche.Bzclwybm;
                                cph = jiayouche.Cph;
                                mc = jiayouche.Clmc;
                            }
                            items.Add(new CheLiangGuZhang { Bzcltid = bzcltid, Bzclid = bzclid, Zbwybm = ssbm/*worksheet.Cells[row, 1].Value?.ToString() ?? ""*/, Mc = mc/*worksheet.Cells[row, 2].Value?.ToString() ?? ""*/, Xh = xh/*worksheet.Cells[row, 3].Value?.ToString() ?? ""*/, Bh = cph/*worksheet.Cells[row, 4].Value?.ToString() ?? ""*/, Fxrq = worksheet.Cells[row, 1].GetValue<DateTime>(), Pcrq = worksheet.Cells[row, 2].GetValue<DateTime>(), Gzxx = worksheet.Cells[row, 3].Value?.ToString() ?? "", Gzyy = worksheet.Cells[row, 4].Value?.ToString() ?? "", Gzfswz = worksheet.Cells[row, 5].Value?.ToString() ?? "", Gzjmc = worksheet.Cells[row, 6].Value?.ToString() ?? "", Gzjxh = worksheet.Cells[row, 7].Value?.ToString() ?? "", Gzjhm = worksheet.Cells[row, 8].Value?.ToString() ?? "", Gzjzjrq = worksheet.Cells[row, 9].GetValue<DateTime>(), Gzjgzsj = worksheet.Cells[row, 10].Value?.ToString() ?? "", Pcff = worksheet.Cells[row, 11].Value?.ToString() ?? "", Pgr = worksheet.Cells[row, 12].Value?.ToString() ?? "", Pggs = worksheet.Cells[row, 13].Value?.ToString() ?? "", Ghjmc = worksheet.Cells[row, 14].Value?.ToString() ?? "", Ghjxh = worksheet.Cells[row, 15].Value?.ToString() ?? "", Ghjhm = worksheet.Cells[row, 16].Value?.ToString() ?? "", Ghjsysj = worksheet.Cells[row, 17].Value?.ToString() ?? "" });
                        }
                        affrows = _fsql.Insert(items).ExecuteAffrows();
                    }
                }
                catch (Exception e)
                {
                    affrows = -1;
                    _logger.LogInformation("导入车辆故障失败：" + e.Message);
                }

            });
            if (affrows == -1)
            {
                return RenderJson(status: "failed", message: "导入车辆故障失败", code: -1);
            }
            return RenderJson(data: affrows);
        }
    }
}
